<?php

require_once("View/View/PageView.php");
require_once("login/src/Model/UserInfo.php");
require_once("Database/Model/UserInfoDAL.php");
require_once("RegisterMember/src/View/RegisterView.php");
require_once("RegisterMember/src/Model/RegisterValidation.php");

class RegisterController
{
	/**
	*@var UserInfoDAL,
	**/
	private $userInfoDAL;
	/**
	*@var PageView,
	**/
	private $pageView;
	/**
	*@var RegisterView,
	**/
	private $registerView;
	/**
	*@var RegisterValidation,
	**/
	private $registerValidation;


	public function __construct()
	{
		$this->pageView = new PageView();
		$this->userInfoDAL = new UserInfoDAL();
		$this->registerView = new RegisterView();
		$this->registerValidation = new RegisterValidation();
	}
	
	/**
	*@return string html
	**/
	public function getPage()
	{
		$this->CheckIfPost();
			
		$errorMessage = $this->registerValidation->getErrorMessage();	
		$title = "Träningsdagboken - Register";
		$head = "";
		$body = $this->registerView->getRegisterPage($errorMessage);

		$html = $this->pageView->getHtmlPage($title, $head, $body);	
		return $html;
	}


	private function CheckIfPost()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST')
		{
			$email = $this->registerView->getEmail();
			$username = $this->registerView->getUsername();
			$password = $this->registerView->getPassword();
			$password2 = $this->registerView->getPassword2();


			if($this->registerValidation->validateRegisterInfo($email, $username, $password, $password2))
			{
				$userinfo = UserInfo::CreateUserInfo($email, $username, $password);

				if(!$this->registerValidation->usernameExists($userinfo))
				{
					$this->userInfoDAL->saveNewUser($userinfo);
					header("Location: ./index.php?newMember"); // skaffa en ny class för redirect, navigation som han har på föreläsningarna.
				}
			}
		}
	}

}